// 题目描述
// 给你一个二进制数组 nums ，你需要从中删掉一个元素。

// 请你在删掉元素的结果数组中，返回最长的且只包含 1 的非空子数组的长度。

// 如果不存在这样的子数组，请返回 0 。

 

// 提示 1：

// 输入：nums = [1,1,0,1]
// 输出：3
// 解释：删掉位置 2 的数后，[1,1,1] 包含 3 个 1 。
// 示例 2：

// 输入：nums = [0,1,1,1,0,1,1,0,1]
// 输出：5
// 解释：删掉位置 4 的数字后，[0,1,1,1,1,1,0,1] 的最长全 1 子数组为 [1,1,1,1,1] 。
// 示例 3：

// 输入：nums = [1,1,1]
// 输出：2
// 解释：你必须要删除一个元素。

// 自己的答案（模仿了上一节）：
/**
 * @param {number[]} nums
 * @return {number}
 */
var longestSubarray = function(nums) {
    let left = 0; // 左指针
    let maxCount = 0; // 最大连续1的个数
    let zeroCount = 0; // 当前窗口内的0的个数
 
    for (let right = 0; right < nums.length; right++) {
        if (nums[right] === 0) {
            zeroCount++; // 遇到0，增加zeroCount
        }
 
        // 如果当前窗口内的0的个数超过了k，需要移动左指针收缩窗口
        while (zeroCount > 1) {
            if (nums[left] === 0) {
                zeroCount--; // 左指针指向0时，减少zeroCount
            }
            left++; // 移动左指针
        }
 
        // 更新最大连续1的个数
        maxCount = Math.max(maxCount, right - left + 1);
    }
 
    return maxCount - 1;
};

// Gpt解法（太复杂了不建议看，思路和自己的一样，看自己的就好）：
function longestSubarray(nums) {
    const n = nums.length;
    
    // Helper function to find the length of the longest contiguous 1s subarray
    function findLongestOnes(arr) {
        let maxLength = 0;
        let currentLength = 0;
        
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] === 1) {
                currentLength++;
                maxLength = Math.max(maxLength, currentLength);
            } else {
                currentLength = 0;
            }
        }
        
        return maxLength;
    }
    
    // Case where the entire array is 1s
    if (nums.every(num => num === 1)) {
        return n - 1; // Since we need to remove one element
    }
    
    let maxLength = 0;
    let left = 0;
    let right = 0;
    let zerosBetween = 0;
    
    while (right < n) {
        if (nums[right] === 0) {
            zerosBetween++;
        }
        
        // Shrink the window from the left if there are more than one zero
        while (zerosBetween > 1) {
            if (nums[left] === 0) {
                zerosBetween--;
            }
            left++;
        }
        
        // Calculate the length of the current window with and without removing an extra zero
        const currentLengthWithZero = right - left;
        const currentLengthWithoutZero = currentLengthWithZero - zerosBetween;
        
        // The longest subarray with one zero removed should be considered as well
        // It means we can have a sequence of 1s which is interrupted by one zero
        maxLength = Math.max(maxLength, currentLengthWithZero - 1, currentLengthWithoutZero);
        
        right++;
    }
    
    // Compare with the case where no element is removed from the entire array
    maxLength = Math.max(maxLength, findLongestOnes(nums));
    
    // Since we need to remove at least one element, if maxLength is the same as the original longest, we need to decrement by 1
    if (maxLength === findLongestOnes(nums)) {
        maxLength -= 1;
    }
    
    // Ensure maxLength is not less than 0 (although it shouldn't be given the problem constraints)
    return Math.max(maxLength, 0);
}

// Test cases
console.log(longestSubarray([1,1,0,1])); // Output: 3
console.log(longestSubarray([0,1,1,1,0,1,1,0,1])); // Output: 5
console.log(longestSubarray([1,1,1])); // Output: 2

// 官方解法（和自己写的思路一样）：
/**
 * @param {number[]} nums
 * @return {number}
 */
var longestSubarray = function (nums) {
    let left = 0, right = 0;
    const len = nums.length;
    let maxLen = 0;
    let freq = 0;
    while (right < len) {
        if (nums[right] === 0) {
            freq++;
        }

        while (freq > 1) {
            if (nums[left] === 0) {
                freq--;
            }
            left++;
        }

        maxLen = Math.max(right - left, maxLen);
        right++;
    }
    return maxLen;
};